package ks.client.controllers.requests;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ks.client.UserContext;
import ks.client.gui.GMGUI;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.table.Table;
import ks.managers.table.TableManager;

/**
 * The controller for the moderator request.
 */
public class ModeratorController implements IProcessMessage {

	/** In case we need to process something. */
	Lobby lobby;
	
	/** Construct controller with lobby. */
	public ModeratorController(Lobby lobby) {
		this.lobby = lobby;
	}

	/**
	 * Client has received moderator message. Process it.
     * 
	 * @param m The message to process.
	 * @return true on success; false on failure.
	 */
	public boolean process(Message m) {
		// Get context
		UserContext context = lobby.getUserContext();
		
		// extract information from the message
		Node moderatorNode = m.contents();
		
		if (moderatorNode == null) {
			return false;
		}
		if (!moderatorNode.getNodeName().equalsIgnoreCase("moderator")) {
			return false;
		}
		
		NamedNodeMap nnp = moderatorNode.getAttributes();
		
		Node tableNode = nnp.getNamedItem("table");
		Node playerNode = nnp.getNamedItem("player");
		
		if (tableNode == null) {
			return false;
		}
		if (playerNode == null) {
			return false;
		}
		
		int tableNum = Integer.parseInt(tableNode.getNodeValue());
		String player = playerNode.getNodeValue();
		
		TableManager tm = context.getTableManager();
		
		Table table = tm.getTable(tableNum);
		
		if (table == null) {
			return false;
		}
		
		table.setModerator(player);
		System.out.println(table.getModerator());
		
		GMGUI gui = lobby.getGMGUI();
		
		if (gui != null)
			gui.updateUserList();
		
		return true;
	}
}
